﻿// ------------------------------------------------------------------------------------
//      Copyright (c) 2012 uhavemyword@gmail.com. All rights reserved.
//      Created by Ben at 12/24/2012 7:13:16 PM
// ------------------------------------------------------------------------------------

namespace CP.NLayer.Service.Services
{
    using CP.General;
    using CP.NLayer.Data;
    using CP.NLayer.Models.Entities;
    using CP.NLayer.Service.Contracts;
    using Microsoft.Practices.Unity;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;

    [ErrorHandlingBehavior]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class UserService : EntityService<User>, IUserService
    {
        #region Private fields
        private ICrypto _crypt;
        #endregion

        #region Ctor
        public UserService()
            : this(null)
        {
        }

        public UserService(IUnitOfWork worker)
            : base(worker)
        {
            this._crypt = DependencyInjection.Container.Resolve<ICrypto>();
        }
        #endregion

        #region IUserService

        public User Login(string username, string password)
        {
            Guard.ThrowIfNull(() => new { username, password });
            User user = Worker.GetRepository<User>().Table
                .Where(x => x.LoginName.ToLower() == username.ToLower() && x.IsActive)
                .Include(x => x.Roles.Select(y => y.Permissions))
                .FirstOrDefault();
            if (user != null && _crypt.IsMatch(password, user.PasswordHash, user.PasswordSalt.GetValue()))
            {
                return user;
            }
            else
            {
                return null;
            }
        }

        #endregion

        public override IList<User> GetPage(int pageIndex, int pageSize)
        {
            return Worker.GetRepository<User>().Table.
                        OrderByDescending(x => x.CreatedOnUtc).Skip(pageIndex * pageSize).Take(pageSize).Include(x => x.Roles).ToList();
        }
    }
}
